package com.sw.haruka.view;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;

import com.shqyang.yexplorer.ExplorerFragment;
import com.shqyang.yexplorer.manager.ExplorerManager;
import com.shqyang.yexplorer.manager.file.FileManager;
import com.shqyang.yexplorer.util.AndroidFileUtils;
import com.sw.haruka.App;
import com.sw.haruka.R;
import com.sw.haruka.dal.HarukaConfig;
import com.sw.haruka.helper.utils.ActivityUtils;
import com.sw.haruka.helper.utils.FileUtils;
import com.sw.haruka.helper.utils.HarukaHandler;
import com.sw.haruka.helper.utils.HarukaHandlerConstant;
import com.sw.haruka.helper.utils.Configuration;
import com.sw.haruka.helper.utils.SoftInputManager;
import com.sw.haruka.helper.utils.StringUtil;
import com.sw.haruka.helper.utils.ToastUtils;
import com.sw.haruka.model.BaseActivity;
import com.sw.haruka.model.DownloadManager;
import com.sw.haruka.model.DownloadObserver;
import com.sw.haruka.model.FileListenerThread;
import com.sw.haruka.model.FileRequestManager;
import com.sw.haruka.model.dialog.DownloadDialog;
import com.sw.haruka.model.dialog.NormalDialog;
import com.sw.haruka.model.entity.FileShareTask;
import com.sw.haruka.module.music.MusicFragment;
import com.sw.haruka.module.search.SearchFragment;
import com.sw.haruka.module.title.TitleMode;
import com.sw.haruka.module.title.TransformerTitleFragment;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import tech.haruka.openutils.PermissionUtil;


public class MainActivity extends BaseActivity implements DownloadObserver {

    private Button mSearchBox;
    private ImageButton mScanQrCode;
    private ImageButton mDownloadMonitor;
    private ProgressBar mDownloading;
    private SearchFragment mSearchFragment;
    private RelativeLayout mLayer2Rl;
    private ExplorerFragment mExplorerFragment;
    private Fragment mLayer2Fragment;

    private ExplorerManager mExplorerManager;

    @Override
    protected int layoutId() {
        return R.layout.main_act;
    }

    @Override
    protected void initView() {
        App.Companion.setHz(getWindowManager().getDefaultDisplay().getRefreshRate());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.title_ll, new TransformerTitleFragment(TitleMode.TITLE_BAR))
                .commit();
        mExplorerFragment = new ExplorerFragment(HarukaConfig.ROOT_PATH);
        mExplorerFragment.setClickAction(new ExplorerFragment.FileClickAction() {
            @Override
            public void openInApp(File file) {
                switch (FileManager.getInstance().getSimpleType(file)) {
                    case MUSIC:
                        showLayer2(new MusicFragment(file));
                        break;
                    default:
                        Toast.makeText(mContext, "暂不支持该类型~", Toast.LENGTH_SHORT).show();
                }
            }

            public void openFile(File file) {
                if (file.isDirectory()) {
                    //search mode, goto folder view
                    String path = file.getPath();
                    startActivity(new Intent(mContext, FolderActivity.class).putExtra("path", path));
                } else {
                    // 打开文件
                    AndroidFileUtils.openFile(mContext, file);
                }
            }

            public void enterCheckMode() {

            }

            public void checkChange(int checkSize) {

            }

            @Override
            public void move(ArrayList<String> checkedFilePathList) {
                Intent intent = new Intent(mContext, FolderActivity.class);
                intent.putExtra("mode", "move");
                intent.putStringArrayListExtra("moveFilePathArray", checkedFilePathList);
                startActivity(intent);
            }
        });
        getSupportFragmentManager().beginTransaction()
                .add(R.id.explorerContainer_rl, mExplorerFragment)
                .commit();
        mLayer2Rl = findViewById(R.id.layer2_rl);
        mSearchBox = findViewById(R.id.button_search);
        mScanQrCode = findViewById(R.id.imageButton_scan);
        mDownloadMonitor = findViewById(R.id.imageButton_download);
        mDownloading = findViewById(R.id.progressBar_downloading);
        FileRequestManager.getInstance().addObserver(this);
        mSearchFragment = new SearchFragment();
        mSearchBox.setOnClickListener(v -> {
            mExplorerManager.setSearchMode();
            showLayer2(mSearchFragment);
        });
        mScanQrCode.setOnClickListener(view -> {
            if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                PermissionUtil.getCameraPermission(MainActivity.this);
                return;
            }
            Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SCAN);
        });
        mDownloadMonitor.setOnClickListener(view -> {
            startActivity(new Intent(MainActivity.this, DownloadMonitorActivity.class));
        });
        mExplorerManager = ExplorerManager.getInstance();
        mHandler = new HarukaHandler(this) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case HarukaHandlerConstant.DOWNLOAD_DONE:
                        toastDownloadDone((String)msg.obj);
                        break;
                    case HarukaHandlerConstant.DOWNLOAD_START:
                        toastDownloadStart((String)msg.obj);
                        break;
                    case HarukaHandlerConstant.DOWNLOAD_CANCEL:
                        toastDownloadCancel((String)msg.obj);
                        break;
                }
            }
        };
    }

    @Override
    protected void loadData(boolean isRefresh) {
        isShowHiddenFile();
    }
    /*
        隐藏文件显示操作
         */
    private void isShowHiddenFile() {
        mExplorerFragment.setShowHiddenFile(Configuration.INSTANCE.getBoolean(Configuration.Keys.ShowHiddenFile));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.INSTANCE.bindMainActivity(this);
        ToastUtils.setContext(getApplicationContext());
    }

    public void showLayer2(Fragment fragment) {
        mLayer2Rl.setVisibility(View.VISIBLE);
        mLayer2Fragment = fragment;
        if (!fragment.isAdded()) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.layer2_rl, fragment)
                    .commit();
        } else {
            getSupportFragmentManager().beginTransaction().show(fragment);
        }
    }

    public boolean exitFragment() {
        if (mLayer2Fragment == null || mLayer2Rl.getVisibility() != View.VISIBLE) {
            return false;
        }
        getSupportFragmentManager().beginTransaction()
                .remove(mLayer2Fragment)
                .commit();
        mLayer2Fragment = null;
        SoftInputManager.hide(this, mLayer2Rl);
        mExplorerManager.setExplorerMode();
        mLayer2Rl.setVisibility(View.GONE);
        return true;
    }

    /*
    下载文件服务
     */
    private DownloadManager mDownloadThread;
    private FileListenerThread mFileListenerThread;
    private void downloadService() {
        if (mDownloadThread == null || mFileListenerThread == null) {
            mDownloadThread = DownloadManager.getInstance();
            mFileListenerThread = new FileListenerThread(HarukaConfig.Deliver_Port);
            mFileListenerThread.start();
        }
        FileUtils.createNewFolder(HarukaConfig.Download_Path);
    }

    /*
    动画
     */
    private void animationGo() {
        mSearchBox.startAnimation(AnimationUtils.makeInAnimation(getApplicationContext(), true));
        mScanQrCode.startAnimation(AnimationUtils.makeInAnimation(getApplicationContext(), false));
        mDownloadMonitor.startAnimation(AnimationUtils.makeInAnimation(getApplicationContext(), false));
    }

    private static HarukaHandler mHandler;

    public static HarukaHandler getHandler() {
        return mHandler;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PermissionUtil.CAMERA_PERMISSION_CODE) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                // 没有获取相关权限，不予加载
                Toast.makeText(this, "没有相机权限，无法使用扫码功能", Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
            }
        }
    }

    private static final int REQUEST_CODE_SCAN = 1000;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                final String text = data.getStringExtra(Constant.CODED_CONTENT);
                try {
                    DownloadDialog dialog = new DownloadDialog(this, mHandler);
                    dialog.setDownloadThread(mDownloadThread);
                    dialog.setQrCodeInfo(text);
                    dialog.show();
                } catch (Exception e) {
                    final NormalDialog dialog = new NormalDialog(MainActivity.this);
                    dialog.getNoButton().setText("关闭");
                    dialog.getYesButton().setText("复制");
                    dialog.setText(text).setYesClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            StringUtil.setClipData(MainActivity.this, text);
                            Toast.makeText(MainActivity.this, "已复制", Toast.LENGTH_SHORT).show();
                            dialog.dismiss();
                        }
                    }).show();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        if (exitFragment() || mExplorerFragment.back2previous()) {
            return;
        }
        finishAffinity();
    }

    @Override
    protected void onResume() {
        super.onResume();
        FileUtils.scan();   // 开始扫描
        downloadService();      // 下载文件服务
        animationGo();      // 加载动画
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileRequestManager.getInstance().removeObserver(this);
        if (mFileListenerThread != null) {
            mFileListenerThread.close();
        }
    }

    @Override
    public void currentTaskList(List<FileShareTask> taskList) {
        runOnUiThread(()->{
            if (taskList.size() == 0) {
                mDownloading.setVisibility(View.GONE);
            } else {
                mDownloading.setVisibility(View.VISIBLE);
            }
        });
    }

}
